'use client';

import { SWRConfig } from 'swr';
import { useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';

type SwrInitorProps = {
  children: ReactNode;
};
const SwrInitor = ({ children }: SwrInitorProps) => {
  const router = useNavigate();
  const [searchParams] = useSearchParams();
  const consoleToken = searchParams.get('console_token');
  const consoleTokenFromLocalStorage = localStorage?.getItem('console_token');
  const [init, setInit] = useState(false);

  useEffect(() => {
    if (!(consoleToken || consoleTokenFromLocalStorage)) router('/signin', { replace: true });

    if (consoleToken) {
      localStorage?.setItem('console_token', consoleToken!);
      router('/apps', { forceOptimisticNavigation: false, replace: true } as any);
    }
    setInit(true);
  }, []);

  return init ? (
    <SWRConfig
      value={{
        shouldRetryOnError: false,
        revalidateOnFocus: false,
      }}
    >
      {children}
    </SWRConfig>
  ) : null;
};

export default SwrInitor;
